package servlet;

import bean.UserInfo;
import util.JwtUtil;
import controller.loginVerify;
import dao.UserDaoImpl;
import org.json.JSONArray;
import org.json.JSONObject;
import pojo.User;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author moyv
 */
public class LoginServlet extends HttpServlet {
    private int account;
    private String psw;
    private String message;

    @Override
    public void init() throws ServletException {
        // 执行必需的初始化
        System.out.println(this.getClass().getName() + "啥，有人在登录");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject reqObj = new JSONObject(req.getParameter("request"));
        account = reqObj.getInt("account");
        psw = reqObj.getString("password");
        loginVerify loginVerify = new loginVerify(account, psw);
        //        以json的形式存储数据
        JSONObject obj = new JSONObject();
        int status = loginVerify.start();
        obj.put("status", status);
//        结果体
//        返回用户信息
        if (status == 1) {
            RedisDao dao = new RedisDaoImpl();
//            添加在线用户
            dao.addOnline(account);
//            查询用户信息
            UserInfo user = dao.getUserInfo(account);
            String token = "";
//            当redis中不存在token时
            if (!dao.isToken(account)) {
                //            进行签证操作

                JwtUtil jwtUtil = new JwtUtil();
                try {
                    token = jwtUtil.createJWT(account, JwtUtil.subject, JwtUtil.key, JwtUtil.ttlMillis);
                } catch (Exception e) {
                    System.out.println(account + "的令牌生成失败");
                }
                dao.addToken(account, token);
            }
            token = dao.getToken(account);
            obj.put("account", user.getAccount());
            obj.put("name", user.getName());
            obj.put("introduction", user.getIntroduction());
            obj.put("token", token);
        }
        // 设置响应内容类型
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(obj);
    }
}
